package controllers;

import java.util.ArrayList;
import java.util.List;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.sparql.engine.http.QueryExceptionHTTP;

import models.Oeuvre;
import play.api.data.*;
import play.data.DynamicForm;
import play.mvc.Controller;
import play.mvc.Result;
import play.data.Form;
import play.Logger;
import play.Play;

public class Recherche extends Controller{
	
	public static final Form<Oeuvre> formrecherche=play.data.Form.form(Oeuvre.class);	
	public static Result rechercher(){		
		
		String param=request().getQueryString("parametre");	
		Model model = ModelFactory.createDefaultModel();	
		//mmmm
		//
		String queryString = 				
				"SELECT DISTINCT ?a ?b ?c "
				+"WHERE {"
				+ "?a ?b ?c ."
				+ "} "
				+"LIMIT 10";
		
		Query query = QueryFactory.create(queryString) ;
	    QueryExecution qexec =    QueryExecutionFactory.sparqlService("http://localhost:9001/sparql/", query);
	    ArrayList<String> resfinal=new ArrayList<String>();
	    int nbr=0;
	    try{
	    	ResultSet resultatsrequete = qexec.execSelect() ;  		    	
	    	while(resultatsrequete.hasNext()){		    		
		    		QuerySolution soln = resultatsrequete.nextSolution();                    
		            resfinal.add(soln.get("?a").toString());
		            resfinal.add(soln.get("?b").toString());
		            resfinal.add(soln.get("?c").toString());
		            nbr++;
	    	}	    		    	
		}
	    catch (QueryExceptionHTTP e) {
	    	 e.getResponseMessage();
	    }
	    finally{qexec.close();}
	   
	    
	    
	    return ok(views.html.home.render(nbr, formrecherche, resfinal));
		
	    //return redirect(routes.Recherche.getResultats(param));		
	}
	public static Result getResultats(String param){	
		SparqlRequests sr=new SparqlRequests(param);		
		List<Oeuvre> res=sr.ExecuteRequete(sr.getParametre());
		Logger.debug("message : %s",param );
		return TODO;///ok(views.html.home.render(param, formrecherche, res));	
	}
	
}
